package com.mamahao.vmnetframework

import android.arch.lifecycle.Observer
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.google.gson.Gson
import com.mamahao.vmnetframework.test.viewmodel.CityViewModel
import com.mamahao.vmnetframework.framework.viewmodel.LViewModelProviders
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private lateinit var cityViewModel: CityViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        cityViewModel = createViewModel()

        getCity.setOnClickListener {
            cityViewModel.queryCityData()
        }

        jumpTest.setOnClickListener {
            cityViewModel.queryCity1Data()
        }
    }

    private fun createViewModel() : CityViewModel {
        return LViewModelProviders.of(this, CityViewModel::class.java).apply {
            oneLiveData.observe(this@MainActivity, Observer {
                println("wo shi shen 请求回来")
                tvContent.text = "第一个${Gson().toJson(it)}"
            })
            twoLiveData.observe(this@MainActivity, Observer {
                println("wo shi shen 请求回来")
                tvContent.text = "第二个${Gson().toJson(it)}"
            })
            errorLiveData.observe(this@MainActivity, Observer {
                if(it == true){
                    Toast.makeText(this@MainActivity, "服务异常", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this@MainActivity, "网络异常", Toast.LENGTH_SHORT).show()
                }
            })
        }
    }
}
